package com.ruoyi.web.controller.sso;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
public class LoginSsoController {
    @Value("${sa-token.sso.check-ticket-url}")
    private String checkTicketUrl;

    @Value("${sa-token.sso.get-data-url}")
    private String getDataUrl;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private TokenService tokenService;

    @PostMapping("/loginSso")
    public AjaxResult loginSso(String token) {
        AjaxResult ajaxResult = null;

        LoginUser user = tokenService.getLoginUserBySsoToken(token);
        System.out.println(user);

        if (user == null) {
            System.out.println("需要登录");
            //这里进行单点登录上级系统的令牌校验 写自己的逻辑
            JSONObject ssoObject = this.checkSsoToken(token);
            Integer code1 = ssoObject.getInteger("code");
            if (code1 == 200) {
                String loginId = ssoObject.getString("data");
                JSONObject userObject = this.getUserData(loginId);

                Integer code2 = userObject.getInteger("code");
                String name = null, pwd = null;
                if (code2 == 200) {//验证成功需要自动登录
                    //拿到登录名和密码
                    name = userObject.getString("name");
                    pwd = userObject.getString("pwd");
                } else {//验证失败返回失败信息
                    ajaxResult = AjaxResult.error(userObject.getString("msg"));
                }

                //组装checkUserNameUnique方法需要的SysUser对象，检测用户名存在否
                SysUser loginUser = new SysUser();
                loginUser.setUserName(name);
                if (UserConstants.NOT_UNIQUE == userService.checkUserNameUnique(loginUser)) {
                    System.out.printf("单点登录用户%s已存在%n", name);
                } else {
                    System.out.printf("单点登录用户%s不存在, 需要创建%n", name);
                    //将上级系统带过来的用户创建个新用户存储起来 TODO
//                SysUser sysUser = this.createSsoUser(ssoObject);
//                userService.insertUser(sysUser);
                }

                // 生成本系统的令牌给到前端进行登录
                ajaxResult = AjaxResult.success();
                // 无验证码登录
                String tokenNew = loginService.loginNoCaptcha(name, pwd, token).get("token").toString();
                System.out.println("tokenNew==" + tokenNew);
                ajaxResult.put("token", tokenNew);
                ajaxResult.put("msg", "登录成功");

            } else {
                ajaxResult = AjaxResult.error(ssoObject.getString("msg"));
            }
        } else {
            System.out.println("无需重复登录");
            Map<String, Object> claims = new HashMap<>();
            claims.put(Constants.LOGIN_USER_KEY, user.getToken());
            // 获取请求携带的令牌
            String ssoToken = tokenService.createToken(claims);
            ajaxResult = AjaxResult.success();
            // 无验证码登录
            ajaxResult.put("token", ssoToken);
            ajaxResult.put("msg", "登录成功");
            System.out.println("ssoToken==" + ssoToken);
        }

        return ajaxResult;
    }

    /**
     * token校验
     */
    JSONObject checkSsoToken(String token) {
        return JSONObject.parseObject(HttpUtil.createGet(checkTicketUrl + "?ticket=" + token).execute().body());
    }

    JSONObject getUserData(String loginId) {
        return JSONObject.parseObject(HttpUtil.createGet(getDataUrl + "?loginId=" + loginId + "&systemType=CBXT").execute().body());
    }

    //组装单点登录的用户对象 将来存入本系统
    SysUser createSsoUser(JSONObject ssoObject) {
        JSONObject dataObject = ssoObject.getJSONObject("data");
        //从父级系统拿到的用户信息
        String userId = dataObject.getString("userId");
        String companyId = dataObject.getString("companyId");
        String companyName = dataObject.getString("companyName");
        String deptId = dataObject.getString("deptId");
        String userName = dataObject.getString("userName");
        String nickName = dataObject.getString("nickName");
        String email = dataObject.getString("email");
        String phonenumber = dataObject.getString("phonenumber");
        String sex = dataObject.getString("sex");
        String avatar = dataObject.getString("avatar");
        //组装本系统用户信息
        SysUser sysUser = new SysUser();
        sysUser.setUserName(userName);
        sysUser.setNickName(nickName);
        sysUser.setPassword(SecurityUtils.encryptPassword("123456"));
        sysUser.setCreateBy("sso");
        sysUser.setCreateTime(new Date());
        sysUser.setDeptId(202L);//所属部门 建议在后管新增一个部门进行初始化
        Long[] roleIds = {100L};
        sysUser.setRoleIds(roleIds);//归属角色  建议在后管新增一个角色进行初始化

        return sysUser;
    }
}
